package www.ym.com.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.tools.jconsole.JConsoleContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.jacoco.agent.rt.internal_f3994fa.core.data.ISessionInfoVisitor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import www.ym.com.common.CustomException;
import www.ym.com.common.R;
import www.ym.com.common.RL;
import www.ym.com.entity.Role;
import www.ym.com.entity.Staff;
import www.ym.com.entity.User;
import www.ym.com.service.UserService;
import www.ym.com.utils.Md5Utils;
import www.ym.com.utils.SMSUtils;
import www.ym.com.utils.TokeUtils;
import www.ym.com.utils.ValidateCodeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import www.ym.com.utils.Md5Utils;

import static www.ym.com.utils.JWTUtils.createJWT;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 利用阿里云发送验证码
     *
     * @param user
     * @param session
     * @return
     */
//    @PostMapping("/sendMsg")
//    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
//        //获取手机号
//        String phone = user.getPhone();
//
//        if (phone != null) {
//            //随机生成的6位随机数
//            String code = ValidateCodeUtils.generateValidateCode(6).toString();
//            log.info("验证码code={}", code);
//
//            //调用阿里云的短信服务api完成短信发送
////            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
//
//            //需要将生成的验证码保存到session
//            session.setAttribute(phone, code);
//            return R.success("已发送验证码至您的手机，请注意查收");
//        }
//        return R.success("发送验证码失败");
//    }

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public R<String> register(@RequestBody User user) {
        //判断手机号的唯一性
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone());
        int count = userService.count(wrapper);
        if (count > 0) {
            log.info("count+" + count);
            throw new CustomException("手机号已注册");
        }

        //保存md5算法后的盐值和密码
        String salt = UUID.randomUUID().toString().toUpperCase();
        user.setSalt(salt);
        String md5Password = Md5Utils.getMd5Password(user.getPassword(), salt);
        user.setPassword(md5Password);
        user.setStatus(1);

        userService.save(user);
        return R.success("", "注册成功");
    }

    @PostMapping("/login")
    public R<Object> login(@RequestBody User user, HttpSession session, HttpServletRequest request) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone());
        User one = userService.getOne(wrapper);
        if (one != null) {
            //用户提交的密码经过加密后与数据库对比
            String md5Password = Md5Utils.getMd5Password(user.getPassword(), one.getSalt());

            //验证信息正确
            if (md5Password.equals(one.getPassword()) && user.getPhone().equals(one.getPhone())) {
                session.setAttribute("userInfo", one);
            }
            log.info("session+" + session.getAttribute("userInfo"));

            //密码或手机号错误
            if (!md5Password.equals(one.getPassword())) {
                throw new CustomException("手机号或密码错误");
            }
            //状态为注销
            if (one.getStatus() == 0) {
                throw new CustomException("账号异常，请联系管理员");
            }
        } else {
            throw new CustomException("手机号或密码错误");
        }

        String token = createJWT(one.getUsername());
        //6.登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("userInfo", one);
        HashMap<String, Object> userInfo = new HashMap<>();

        userInfo.put("user", one);
        userInfo.put("token", token);

        return R.success(userInfo, "登录成功");
    }


    /**
     * 重置密码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/reset")
    public R<String> updatePassword(@RequestBody User user, HttpSession session) {
        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Password = Md5Utils.getMd5Password(user.getPassword(), salt);
        //替换盐值和密码
        user.setSalt(salt);
        user.setPassword(md5Password);

        //根据电话号码查询数据库数据
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone());
        User one = userService.getOne(wrapper);

        user.setId(one.getId());
        userService.updateById(user);

        //重置cookie
        session.setAttribute("userInfo", user);
        return R.success(null, "修改成功");
    }


    /**
     * 客户端已登录重置密码
     *
     * @param
     * @param session
     * @return
     */
    @PostMapping("/resetPw")
    public R<String> updateLoginPassword(@RequestBody JSONObject jsonObject, HttpSession session) {

        Long id = Long.valueOf(String.valueOf(jsonObject.get("id")));
        String originalPw = String.valueOf(jsonObject.get("originalPw"));
        String changePw = String.valueOf(jsonObject.get("changePw"));

        // 查询该用户比对原始数据是否一致
        User user = userService.getById(id);
        String md5Password1 = Md5Utils.getMd5Password(originalPw, user.getSalt());

        if(!md5Password1.equals(user.getPassword()) ){
            throw  new CustomException("原始密码错误");
        }else{
            String salt = UUID.randomUUID().toString().toUpperCase();
            String md5Password = Md5Utils.getMd5Password(changePw, salt);
            //替换盐值和密码
            user.setSalt(salt);
            user.setPassword(md5Password);
        }
        userService.updateById(user);
        //重置cookie
        session.setAttribute("userInfo", user);
        return R.success(null, "修改成功");
    }

    /**
     * 分页查询
     *
     * @param jsonObject
     * @return
     */

//    @Transactional
    @PostMapping("/list")
    public RL<User> page(@RequestBody JSONObject jsonObject) {
        Page<User> userPage = userService.pageUser(jsonObject);
        List<User> records = userPage.getRecords();
        long total = userPage.getTotal();
        long pageNum = userPage.getCurrent();
        long pageSize = userPage.getSize();
        return RL.listSuccess(records, null, total, pageNum, pageSize);
    }

    /**
     * 修改用户状态
     *
     * @param
     * @return
     */
    @Transactional
    @PostMapping("/update/{status}")
    public R<String> update(@PathVariable Integer status, @RequestBody Long id) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, id);
        User one = userService.getOne(wrapper);
        one.setStatus(status);
        userService.updateById(one);
        return R.success(null, "修改成功");
    }

    /**
     * 客户端用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/info")
    public R<User> userInfo(Long id) {
        User byId = userService.getById(id);
        return R.success(byId, "处理成功");
    }

    /**
     * 客户端修改用户信息
     *
     * @return
     */
    @PostMapping("/update")
    public R<String> update(@RequestBody User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone());
        int count = userService.count(wrapper);
        if (count > 1) {
            throw new CustomException("手机号码已被使用");
        }
        userService.updateById(user);
        return R.success("", "修改成功");
    }


    /**
     * 退出登录
     *
     * @param
     * @return
     */
//    @PostMapping("/loginout")
//    public R<String> loginout(HttpServletRequest request) {
//        //删除session中的user
//        request.removeAttribute("user");
//        return R.success("退出成功");
//    }

//    @PostMapping("/register")
//    public R<String> register(@RequestBody User user) {
//        //用户名未注册，则可以注册
//        String salt = UUID.randomUUID().toString().toUpperCase();  //随机获取盐值
//        user.setSalt(salt);
//        //将密码和盐值作为一个整体进行加密处理,忽略原有密码强度提升了数据的安全性,使用MD5算法
//        String password = Md5Utils.getMd5Password(user.getPassword(), salt);
//        user.setSalt(password);
//
////        判斷用戶名和手機號是否唯一
//        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        LambdaQueryWrapper<User> username = queryWrapper.eq(User::getUsername, user.getUsername());
//        LambdaQueryWrapper<User> phone = queryWrapper.eq(User::getPhone, user.getPhone());
//        int usernameCount = userService.count(username);
//        int phoneCount = userService.count(phone);
//        if (usernameCount > 0) {
//            return R.error("用户名已注册");
//        }
//        if (phoneCount > 0) {
//            return R.error("手机号已注册");
//        }
//
//        userService.save(user);
//
//        return R.success("注册成功");
//    }
}
